﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BP.OA.Message;
using System.Text;
using System.Data;

namespace CCOA.App.Message
{
    public partial class EditMsg : System.Web.UI.Page
    {
        #region //1.公共接口(Public Interface)
        //权限控制
        private string FuncNo = null;
        private void Alert(string msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        private int rID
        {
            get { return Convert.ToInt32(this.Request.QueryString["ID"]); }
        }
        /// <summary>
        /// 获取路径函数
        /// </summary>
        /// <returns></returns>
        private string GetAttachPathName()
        {
            string dir = String.Format("/DataUser/UploadFile/Message/{0:yyyyMMdd}", DateTime.Now);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        /// <summary>
        /// 根据存储路径获取老文件名，必须是存储路径中包含老文件名才可。
        /// </summary>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private string GetAttachOldFileName(string savePath)
        {
            String attachFile = System.IO.Path.GetFileName(savePath);
            String ext = System.IO.Path.GetExtension(savePath);
            //String[] arr_attachFile = attachFile.Split('_');
            //return String.Format("{0}{1}", arr_attachFile[0], ext);
            int index = attachFile.LastIndexOf('_');
            string oldName = attachFile.Substring(0, index);
            return String.Format("{0}{1}", oldName, ext);
        }
        public string GetAllAttachStr(string savePath, string splitter, string linkFormat)
        {
            if (splitter == null) splitter = ""; //"&nbsp;&nbsp;";
            if (String.IsNullOrEmpty(linkFormat)) linkFormat = "<a href='{1}'>{0}</a>";
            StringBuilder sb = new StringBuilder();
            String[] attachFiles = savePath.Split(new String[] { ";", ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (String attachFile in attachFiles)
            {
                if (sb.Length > 0) sb.Append(splitter);
                sb.AppendFormat(linkFormat
                    , this.GetAttachOldFileName(attachFile)
                    , attachFile);
            }
            return sb.ToString();
        }
        public string GetUserNames(object userNos)
        {
            String users = String.Format("{0}", userNos);
            return BP.OA.GPM.GetUserNames(users);
        }
        #endregion

        #region //2.页面装载(Page Load)
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.LoadData();
            }
        }
        private void LoadData()
        {
            BP.OA.Message.DraftBox dfb = new DraftBox();
            dfb.OID = this.rID;
            int iR = dfb.RetrieveFromDBSources();
            
            if (iR == 0) return;

            BP.OA.Message.Message mes = new BP.OA.Message.Message();
            mes.OID = dfb.FK_MsgNo;
            mes.RetrieveFromDBSources();

            this.txt_UserNames.Value = mes.SendToUsers;
            this.txt_CopyUserNames.Value = mes.CopyToUsers;
            this.txtContent.Text = mes.Doc;
            this.txt_Title.Text = mes.Title;
            this.txt_Users.Text = this.GetUserNames(mes.SendToUsers);
            this.txt_CopyUsers.Text = this.GetUserNames(mes.CopyToUsers);

            this.hfAttachFiles.Value = mes.AttachFile;
            this.liAttachFiles.Text = this.GetAllAttachStr(mes.AttachFile, " ", "<div class='multi-old-div'><a href='#' class='multi-old-remove'>x</a>&nbsp;<a class='multi-old-url' href='{1}'>{0}</a></div>");

            //this.hlFile.Text = this.GetAttachOldFileName(mes.AttachFile);
            //this.hlFile.NavigateUrl = mes.AttachFile;
        }
        private void ClearCtrl()
        {
            this.txt_UserNames.Value = String.Empty;
            this.txt_Users.Text = String.Empty;
            this.txtContent.Text = String.Empty;
        }
        #endregion
        
        #region //3.页面事件(Page Event)
        /// <summary>
        /// 发送 信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSendMsg_Click(object sender, EventArgs e)
        {
            // 1.获取UI值   
            string users = this.txt_UserNames.Value;
            string copyUsers = this.txt_CopyUserNames.Value;
            string title = this.txt_Title.Text.ToString();
            string content = this.txtContent.Text;
            //string names = this.txt_Users.Text;
            string AttachFile = this.hfAttachFiles.Value;
            //附件
            
            // 2.验证   
            if (string.IsNullOrEmpty(users))
            {
                this.Alert("收件人不能为空"); return;
            }
            if (string.IsNullOrEmpty(title))
            {
                this.Alert("邮件标题不能为空"); return;
            } 
            if (string.IsNullOrEmpty(content))
            {
                this.Alert("信息内容不能为空"); return;
            }
            // 3.数据处理
            //3.1.文件删除
            if (!String.IsNullOrEmpty(AttachFile))
            {
                StringBuilder sbOldFile = new StringBuilder();
                String[] oldFiles = AttachFile.Split(new String[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String oldFile in oldFiles)
                {
                    if (oldFile.StartsWith("#"))
                    {
                        System.IO.File.Delete(Server.MapPath(oldFile.Substring(1)));
                    }
                    else
                    {
                        sbOldFile.AppendFormat("{0};", oldFile);
                    }
                }
                AttachFile = sbOldFile.ToString();
            }
            //3.2.文件夹检测
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            //3.3.多文件上传

            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);

                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                        //System.IO.File.Delete(Server.MapPath(hlFile.NavigateUrl));
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            BP.OA.Message.DraftBox dfb = new DraftBox();
            dfb.OID = this.rID;
            int iR = dfb.RetrieveFromDBSources();

            if (iR == 0) return;

            BP.OA.Message.Message msg = new BP.OA.Message.Message();
            msg.OID = dfb.FK_MsgNo;
            msg.RetrieveFromDBSources();
            msg.AddTime = DateTime.Now;
            msg.Doc = content;
            msg.Title = title;
            msg.FK_UserNo = BP.Web.WebUser.No;
            msg.MessageState = 1;
            msg.SendToUsers = users;
            msg.CopyToUsers = copyUsers;
            iR = msg.Update();
            //发送邮件后，草稿删除
            dfb.Delete();

            if (iR == 0)
            {
                this.Alert("消息发送失败！"); return;
            }
            if (true)
            {  //发件箱
                BP.OA.Message.SendBox sb = new BP.OA.Message.SendBox();
                sb.FK_MsgNo = msg.OID;
                sb.FK_SendUserNo = BP.Web.WebUser.No;
                sb.Receiver = users;
                sb.SendTime = DateTime.Now;                
                sb.Insert();
            }
            if (true)
            {   //发送给收件人
                String[] arr_users = users.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String user in arr_users)
                {   //收件箱 n个人
                    BP.OA.Message.InBox ib = new BP.OA.Message.InBox();
                    ib.AddTime = DateTime.Now;
                    ib.FK_MsgNo = msg.OID;
                    ib.FK_ReceiveUserNo = user;
                    ib.Sender = BP.Web.WebUser.No;
                    ib.Received = false;
                    ib.IsCopy = false;  //是否抄送标志
                    ib.Insert();
                }
            }
            if (true)
            {   //发送给抄送人
                String[] arr_users = copyUsers.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String user in arr_users)
                {   //收件箱 n个人
                    BP.OA.Message.InBox ib = new BP.OA.Message.InBox();
                    ib.AddTime = DateTime.Now;
                    ib.FK_MsgNo = msg.OID;
                    ib.FK_ReceiveUserNo = user;
                    ib.Sender = BP.Web.WebUser.No;
                    ib.Received = false;
                    ib.IsCopy = true;  //是否抄送标志
                    ib.Insert();
                }
            }
            // 4.数据统计、日志
            // 5.提交或返回D:\ccflow\CCPortal\CCOA\CCOA\App\Message\SendBox.aspx
            this.Response.Redirect("../../App/Message/SendBox.aspx", true);
            //this.Alert(String.Format("消息发送成功，发送给人员（{0}）！",names));
            //this.ClearCtrl();
        }
        protected void btnSaveMsg_Click(object sender, EventArgs e)
        {
            // 1.获取UI值   
            string users = this.txt_UserNames.Value;
            string copyUsers = this.txt_CopyUserNames.Value;
            string title = this.txt_Title.Text.ToString();
            string content = this.txtContent.Text;
            //string names = this.txt_Users.Text;
            string AttachFile = this.hfAttachFiles.Value;
            //附件

            // 2.验证   
            if (string.IsNullOrEmpty(users))
            {
                this.Alert("收件人不能为空"); return;
            }
            if (string.IsNullOrEmpty(content))
            {
                this.Alert("信息内容不能为空"); return;
            }
            // 3.数据处理
            //3.1.文件删除
            if (!String.IsNullOrEmpty(AttachFile))
            {
                StringBuilder sbOldFile = new StringBuilder();
                String[] oldFiles = AttachFile.Split(new String[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String oldFile in oldFiles)
                {
                    if (oldFile.StartsWith("#"))
                    {
                        System.IO.File.Delete(Server.MapPath(oldFile.Substring(1)));
                    }
                    else
                    {
                        sbOldFile.AppendFormat("{0};", oldFile);
                    }
                }
                AttachFile = sbOldFile.ToString();
            }
            //3.2.文件夹检测
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            //3.3.多文件上传
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);

                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                        //System.IO.File.Delete(Server.MapPath(hlFile.NavigateUrl));
                    }
                    catch
                    {
                        ;
                    }
                }
            }

            BP.OA.Message.DraftBox dfb = new DraftBox();
            dfb.OID = this.rID;
            int iR = dfb.RetrieveFromDBSources();

            if (iR == 0) return;

            BP.OA.Message.Message msg = new BP.OA.Message.Message();
            msg.OID = dfb.FK_MsgNo;
            msg.RetrieveFromDBSources();

            msg.AddTime = DateTime.Now;
            msg.Doc = content;
            msg.Title = title;
            msg.FK_UserNo = BP.Web.WebUser.No;
            msg.MessageState = 1;
            msg.SendToUsers = users;
            msg.CopyToUsers = copyUsers;
            msg.AttachFile = AttachFile;
            msg.Update();

            if (msg.OID == 0)
            {
                this.Alert("消息保存到草稿箱失败！"); return;
            }
            if (true)
            {//草稿箱
                dfb.AddTime = DateTime.Now;
                dfb.Update();
            }
            // 4.数据统计、日志
            // 5.提交或返回        D:\ccflow\CCPortal\CCOA\CCOA\App\Message\DraftBox.aspx    
            this.Response.Redirect("../../App/Message/DraftBox.aspx");
            //this.Alert(String.Format("消息成功保存到草稿箱！"));            
            //this.ClearCtrl();
        }

        #endregion

    }
}